package com.teacher.game.framework.util;

import android.util.Log;

/**
 * 性能优化验证器 - 验证游戏性能优化效果
 * 提供A/B测试功能，对比优化前后的性能指标
 */
public class PerformanceValidator {
    
    private static final String TAG = "PerformanceValidator";
    
    private static PerformanceValidator instance;
    
    // 性能基线
    private static final float TARGET_FPS = 60.0f;
    private static final float ACCEPTABLE_FPS = 45.0f;
    private static final float MAX_RENDER_TIME = 16.67f; // 60fps = 16.67ms per frame
    private static final float MAX_MEMORY_USAGE = 0.75f; // 75% max memory
    
    // 测试统计
    private int testFrames = 0;
    private long testStartTime = 0;
    private boolean isValidating = false;
    
    // 优化效果统计
    private int framesAboveTarget = 0;
    private int framesAboveAcceptable = 0;
    private int renderTimeViolations = 0;
    private int memoryViolations = 0;
    
    /**
     * 获取单例实例
     */
    public static synchronized PerformanceValidator getInstance() {
        if (instance == null) {
            instance = new PerformanceValidator();
        }
        return instance;
    }
    
    /**
     * 开始性能验证测试
     * @param testDurationSeconds 测试持续时间（秒）
     */
    public void startValidation(int testDurationSeconds) {
        if (isValidating) {
            Log.w(TAG, "性能验证已在进行中");
            return;
        }
        
        isValidating = true;
        testStartTime = System.currentTimeMillis();
        testFrames = 0;
        
        // 重置统计
        framesAboveTarget = 0;
        framesAboveAcceptable = 0;
        renderTimeViolations = 0;
        memoryViolations = 0;
        
        Log.i(TAG, "开始性能验证测试，持续时间: " + testDurationSeconds + "秒");
        
        // 自动结束测试
        new Thread(() -> {
            try {
                Thread.sleep(testDurationSeconds * 1000);
                endValidation();
            } catch (InterruptedException e) {
                Log.e(TAG, "性能验证测试被中断", e);
            }
        }).start();
    }
    
    /**
     * 记录性能数据（每帧调用）
     */
    public void recordFrame() {
        if (!isValidating) return;
        
        PerformanceMonitor monitor = PerformanceMonitor.getInstance();
        testFrames++;
        
        // 检查FPS性能
        float currentFPS = monitor.getCurrentFPS();
        if (currentFPS >= TARGET_FPS) {
            framesAboveTarget++;
        }
        if (currentFPS >= ACCEPTABLE_FPS) {
            framesAboveAcceptable++;
        }
        
        // 检查渲染时间
        float renderTime = monitor.getAverageRenderTime();
        if (renderTime > MAX_RENDER_TIME) {
            renderTimeViolations++;
        }
        
        // 检查内存使用
        float memoryUsage = monitor.getCurrentMemoryUsage();
        if (memoryUsage > MAX_MEMORY_USAGE) {
            memoryViolations++;
        }
    }
    
    /**
     * 结束性能验证
     */
    public void endValidation() {
        if (!isValidating) return;
        
        isValidating = false;
        long testDuration = System.currentTimeMillis() - testStartTime;
        
        generateValidationReport(testDuration);
    }
    
    /**
     * 生成验证报告
     */
    private void generateValidationReport(long testDurationMs) {
        float testDurationSeconds = testDurationMs / 1000.0f;
        
        // 计算性能指标
        float targetFpsRate = testFrames > 0 ? (framesAboveTarget * 100.0f / testFrames) : 0;
        float acceptableFpsRate = testFrames > 0 ? (framesAboveAcceptable * 100.0f / testFrames) : 0;
        float renderViolationRate = testFrames > 0 ? (renderTimeViolations * 100.0f / testFrames) : 0;
        float memoryViolationRate = testFrames > 0 ? (memoryViolations * 100.0f / testFrames) : 0;
        
        // 生成报告
        StringBuilder report = new StringBuilder();
        report.append("=== 性能优化验证报告 ===\n");
        report.append(String.format("测试持续时间: %.1f秒\n", testDurationSeconds));
        report.append(String.format("总测试帧数: %d\n", testFrames));
        report.append(String.format("平均FPS: %.1f\n", testFrames / testDurationSeconds));
        report.append("\n--- 性能达标率 ---\n");
        report.append(String.format("目标FPS达标率 (≥%.0f FPS): %.1f%% (%d/%d)\n", 
                     TARGET_FPS, targetFpsRate, framesAboveTarget, testFrames));
        report.append(String.format("可接受FPS达标率 (≥%.0f FPS): %.1f%% (%d/%d)\n", 
                     ACCEPTABLE_FPS, acceptableFpsRate, framesAboveAcceptable, testFrames));
        report.append(String.format("渲染时间违规率 (>%.1fms): %.1f%% (%d/%d)\n", 
                     MAX_RENDER_TIME, renderViolationRate, renderTimeViolations, testFrames));
        report.append(String.format("内存使用违规率 (>%.0f%%): %.1f%% (%d/%d)\n", 
                     MAX_MEMORY_USAGE * 100, memoryViolationRate, memoryViolations, testFrames));
        
        // 性能评级
        String performanceGrade = getPerformanceGrade(targetFpsRate, renderViolationRate, memoryViolationRate);
        report.append(String.format("\n--- 性能评级: %s ---\n", performanceGrade));
        
        // 优化建议
        report.append(getOptimizationSuggestions(targetFpsRate, renderViolationRate, memoryViolationRate));
        
        Log.i(TAG, report.toString());
        
        // 检查是否通过验证
        boolean passed = acceptableFpsRate >= 90.0f && 
                        renderViolationRate <= 10.0f && 
                        memoryViolationRate <= 5.0f;
        
        Log.i(TAG, passed ? "✅ 性能优化验证通过!" : "❌ 性能优化需要进一步改进");
    }
    
    /**
     * 获取性能评级
     */
    private String getPerformanceGrade(float targetFpsRate, float renderViolationRate, float memoryViolationRate) {
        if (targetFpsRate >= 95.0f && renderViolationRate <= 2.0f && memoryViolationRate <= 1.0f) {
            return "S级 (优秀)";
        } else if (targetFpsRate >= 85.0f && renderViolationRate <= 5.0f && memoryViolationRate <= 3.0f) {
            return "A级 (良好)";
        } else if (targetFpsRate >= 70.0f && renderViolationRate <= 10.0f && memoryViolationRate <= 5.0f) {
            return "B级 (合格)";
        } else if (targetFpsRate >= 50.0f && renderViolationRate <= 20.0f && memoryViolationRate <= 10.0f) {
            return "C级 (基本可用)";
        } else {
            return "D级 (需要优化)";
        }
    }
    
    /**
     * 获取优化建议
     */
    private String getOptimizationSuggestions(float targetFpsRate, float renderViolationRate, float memoryViolationRate) {
        StringBuilder suggestions = new StringBuilder();
        suggestions.append("\n--- 优化建议 ---\n");
        
        if (targetFpsRate < 90.0f) {
            suggestions.append("• FPS性能需要改善，考虑减少每帧计算量\n");
        }
        
        if (renderViolationRate > 10.0f) {
            suggestions.append("• 渲染时间过长，建议优化绘制流程和使用渲染缓存\n");
        }
        
        if (memoryViolationRate > 5.0f) {
            suggestions.append("• 内存使用率偏高，建议加强对象池和内存回收\n");
        }
        
        if (targetFpsRate >= 90.0f && renderViolationRate <= 10.0f && memoryViolationRate <= 5.0f) {
            suggestions.append("• 性能表现良好，可以考虑增加更多游戏特效和功能\n");
        }
        
        return suggestions.toString();
    }
    
    /**
     * 获取当前验证状态
     */
    public boolean isValidating() {
        return isValidating;
    }
    
    /**
     * 获取测试进度
     */
    public String getProgress() {
        if (!isValidating) return "未在测试";
        
        long elapsed = System.currentTimeMillis() - testStartTime;
        return String.format("测试进行中: %d帧, %.1f秒", testFrames, elapsed / 1000.0f);
    }
}